﻿package com.thomasbrault.display
{
	import flash.display.MovieClip;
	import flash.events.Event;	

	/**
	 * @author thomas
	 */
	public class AbstractMovieClip extends MovieClip 
	{

		protected var _defaultFrame : uint = 1;
		
		/**
		 * 
		 */
		public function AbstractMovieClip()
		{
			addEventListener( Event.ADDED_TO_STAGE, __onAddedToStage );
			addEventListener( Event.REMOVED_FROM_STAGE, __onRemovedFromStage );	
		}

		
		/**
		 * added to stage
		 */
		private function __onAddedToStage ( e : Event ) : void 
		{
			_addedToStage();
			stage.addEventListener( Event.RESIZE, __onResize );
			__onResize(null);
		}
		
		
		/**
		* 
		*/
		private function __onResize( e : Event ) : void
		{
			_layout();
		}
		
		
		/**
		 * 
		 */
		public function __onRemovedFromStage ( e : Event ) : void 
		{
			removeEventListener( Event.ENTER_FRAME, __onReverse );
			stage.removeEventListener( Event.RESIZE, __onResize );
			_removedFromStage();
		}
		
		
		/**
		* Called function for the layout (when the clip is attached or on resize)
		*/
		protected function _layout ( ) : void
		{
			
		}
		
		
		/**
		* clip is added to stage
		*/
		protected function _addedToStage ( ) : void
		{
			
		}
		
		/**
		* clip is remove from stage
		*/
		protected function _removedFromStage ( ) : void
		{
			
		}
		
		/**
		* play toward to the default frame (1 by default)
		*/
		protected function playToward ( defaultFrame : uint = 1 ) : void
		{
			
			_defaultFrame=defaultFrame;
			addEventListener( Event.ENTER_FRAME, __onReverse );
			
		}
		
		/**
		 * 
		 */
		private function __onReverse(event : Event) : void
		{

			gotoAndStop(currentFrame-1);
			if ( currentFrame == _defaultFrame )
				__stopReverse();
			
		}
		
		/**
		* 
		*/
		private function __stopReverse ( ) : void
		{
			removeEventListener(Event.ENTER_FRAME, __onReverse);
		}
		
		/**
		* cancel the toward when gotoAndPlay method called
		*/
		override public function gotoAndPlay ( frame : Object, scene: String = null ) : void
		{
			__stopReverse();
			super.gotoAndPlay(frame,scene);
		}
		
		/**
		* cancel the toward when play method called
		*/
		override public function play ( ) : void
		{
			__stopReverse();
			super.play();
		}
		
		/**
		* cancel the toward when stop method called
		*/
		override public function stop ( ) : void
		{
			__stopReverse();
			super.stop();
		}
	}
}
